package com.zym.application.controller.tms.shipment;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.zym.application.column.BaseData;
import com.zym.application.config.SystemConfig;
import com.zym.application.controller.tms.order.TmsOrderFromController;
import com.zym.application.model.ReturnModel;
import com.zym.application.session.Http;
import com.zym.application.session.HttpCall;
import com.zym.application.utils.DateUtils;
import com.zym.application.utils.StringUtils;
import com.zym.framework.alert.AlertUtils;
import com.zym.framework.combobox.ZymComboBox;
import com.zym.framework.datetimepicker.DateTimePicker;
import com.zym.framework.form.ZymCallBack;
import com.zym.framework.form.ZymForm;
import com.zym.framework.grid.ZymGrid;
import com.zym.framework.notice.NoticeUtils;
import com.zym.framework.winTool.WinTool;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.fxml.Initializable;
import javafx.scene.Parent;
import javafx.scene.control.*;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.AnchorPane;
import javafx.scene.layout.HBox;
import javafx.scene.paint.Paint;
import javafx.scene.web.WebEngine;
import javafx.scene.web.WebView;
import javafx.util.Callback;

import java.net.URL;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.ResourceBundle;

/**
 * QQ 165149324
 * 臧英明
 *
 * @author
 * @create 2021-03-12
 */
public class TmsOperationController implements Initializable {
    @FXML
    public ZymComboBox select;
    @FXML
    public Label COUNT;
    @FXML
    public Label AUTO_COUNT;
    @FXML
    public WebView webView;
    @FXML
    public Label CODE;
    @FXML
    public Label LICENSE_NUMBER;
    @FXML
    public Label DRIVER;
    @FXML
    public Label TrackModel;
    @FXML
    public Label DESPATCH_TIME;
    @FXML
    public Label ESTIMATE_ARRIVE_TIME;
    @FXML
    public Label alreadyTime;
    @FXML
    public Label orderCode;
    @FXML
    private TextField itemName;
    @FXML
    public AnchorPane tablePane;
    private FXMLLoader fxmlLoader;
    private ZymGrid zymGrid;
    private ZymForm zymForm;
    private String fromXmlPath = "/view/tms/order/tms-order-from.fxml";
    @Override
    public void initialize(URL location, ResourceBundle resources) {
        initGrid();
        initData();
        initMap();
    }
    public void initMap(){
        WebEngine engine = webView.getEngine();
        URL resource = getClass().getResource("/");
        engine.load(resource.toString()+"view/tms/amapMap/map.html");
    }
    private void initData() {
        updateMainData();
        queryList();
    }
    public void updateMainData(){
        Http.post("/tmsshipment/initShipment", null, new HttpCall() {
            @Override
            public void exe(ReturnModel returnModel) {
                JSONObject obj = (JSONObject) returnModel.getObj();
                COUNT.setText(obj.getString("COUNT"));
                AUTO_COUNT.setText(obj.getString("AUTO_COUNT"));
            }
        });
    }
    public void queryList(){
        updateMainData();
        Map map= new HashMap();
        if(StringUtils.isNotEmpty(itemName.getText())){
            map.put("sqlWhereNameToLike",select.getValue().getId());
            map.put("sqlWhereValueToLike",itemName.getText());
        }
        zymGrid.query(map);
    }
    private void initGrid() {
        SystemConfig instance = SystemConfig.getInstance();
        JSONObject dataBook = instance.getDataBook();
        JSONObject TrackModelDataBook = dataBook.getJSONObject("TrackModel");
        this.fxmlLoader = ZymGrid.create();
        DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        this.zymGrid = fxmlLoader.getController();
        Map databook = new HashMap();
        databook.put("STATE","CommState");
        databook.put("TRANSPORT_TYPE","TransportType");
        databook.put("TRACK_MODEL","TrackModel");
        this.zymForm = new ZymForm(null,"/tmsorder/get",fromXmlPath,"订单管理");
        TmsOrderFromController controller = zymForm.getController(TmsOrderFromController.class);
        zymForm.setFormCallback(new ZymCallBack(){
            @Override
            public void getStart(Map map){
                JSONObject jsonObject = new JSONObject(map);
                JSONObject bean = jsonObject.getJSONObject("bean");
                JSONArray cList = jsonObject.getJSONArray("cList");
                JSONArray sList = jsonObject.getJSONArray("sList");
                JSONArray products = jsonObject.getJSONArray("products");
                int order_audit = SystemConfig.getInstance().getOrgConfig().getIntValue("ORDER_AUDIT");
                int state = bean.getIntValue("STATE");
                controller.lockFrom(true);
                zymForm.lockSaveButton(true);
//                if(this.bean.STATE <   this.$store.state.app.tmsSystem.ORDER_AUDIT){
//                    this.view=false
//                }else {
//                    this.view=true
//                }
                map.clear();
                map.putAll(bean);
                controller.setCledgerItems(cList);
                controller.setProductItems(products);
                controller.setSledgerItems(sList);
            }
        });


        zymGrid.initView("/tmsshipment/listShipment",BaseData.OPERATION,databook);
        zymGrid.setWinWidth(1590);
        zymGrid.setRowFactory(new Callback<TableView, TableRow>() {
            @Override
            public TableRow call(TableView param) {
                TableRow<JSONObject> row = new TableRow<JSONObject>();
                row.setOnMouseClicked(event -> {
                    JSONObject jsonObject = row.getItem();
                    System.out.println(jsonObject);
                    CODE.setText(jsonObject.getString("CODE"));
                    //订单号，待处理
                    String tms_order_code = jsonObject.getString("TMS_ORDER_CODE");
                    String[] split = tms_order_code.split(",");
                    HBox hBox = new HBox();
                    for (int i = 0; i <split.length ; i++) {
                        Label label = new Label(split[i]);
                        label.setTextFill(Paint.valueOf("#2d8cf0"));
                        hBox.getChildren().add(label);
                        label.setOnMouseClicked(new EventHandler<MouseEvent>() {
                            @Override
                            public void handle(MouseEvent event) {
                                Label source = (Label) event.getSource();
                                String text = source.getText();
                              zymForm.openForCode(text,"/tmsorder/openForCode");
                            }
                        });
                    }
                    orderCode.setGraphic(hBox);
//                    orderCode.setText(jsonObject.getString("TMS_ORDER_CODE"));
//                    HBox hBox = new HBox();
//
//
//                    orderCode.setGraphic(hBox);
                    LICENSE_NUMBER.setText(jsonObject.getString("LICENSE_NUMBER"));
                    DRIVER.setText(jsonObject.getString("DRIVER"));
                    TrackModel.setText(TrackModelDataBook.getString(jsonObject.getString("TRACK_MODEL")));
                    DESPATCH_TIME.setText(jsonObject.getString("DESPATCH_TIME"));
                    ESTIMATE_ARRIVE_TIME.setText(jsonObject.getString("ESTIMATE_ARRIVE_TIME"));
                    LocalDateTime ldt = LocalDateTime.parse(jsonObject.getString("DESPATCH_TIME"),df);
                    LocalDateTime now = LocalDateTime.now();
                    alreadyTime.setText(DateUtils.bettonStartEnd(ldt,now));
                });
                return row ;
            }
        });
        zymGrid.setWinHeight(175);
        select.getItems().setAll( zymGrid.getSelectModels());
        Parent root = this.fxmlLoader.getRoot();
        tablePane.getChildren().add(root);
    }
    public void view(){
        AlertUtils.error("C/S端未完成，请查看B/S端");
    }

    public void untask(ActionEvent actionEvent) {
        List<String> ids= zymGrid.getSelectId();
        if(ids.size() == 0){
            NoticeUtils.error("请勾选要更改的数据");
            return;
        }
        String str = "条数据反发运？";
        if(!AlertUtils.confirmYesNoConfirmation("通知","您确定要对这"+ids.size()+str)){
            return;
        }
        JSONObject par = new JSONObject();
        par.put("ids",ids);
        Http.post("/tmsshipment/unTask", par, new HttpCall() {
            @Override
            public void exe(ReturnModel returnModel) {
                if (returnModel.isSuceess()){
                    NoticeUtils.success(returnModel.getObj().toString());
                    queryList();
                    updateMainData();
                }else {
                    NoticeUtils.error(returnModel.getObj().toString());
                }

            }
        });
    }

    public void openArrivedFrom(MouseEvent mouseEvent) {
        List<String> ids= zymGrid.getSelectId();
        if(ids.size() == 0){
            NoticeUtils.error("请勾选要更改的数据");
            return;
        }
        WinTool winTool = new WinTool("到达时间");
        winTool.setHeightWidth(50,200);
        Button button = new Button("到达");
        DateTimePicker dateTimePicker = new DateTimePicker();
        winTool.setNode(dateTimePicker);

        button.setOnAction(new EventHandler<ActionEvent>() {
            @Override
            public void handle(ActionEvent event) {
                String str = "条数据进行到达操作？";
                if(!AlertUtils.confirmYesNoConfirmation("通知","您确定要对这"+ids.size()+str)){
                    return;
                }
                JSONObject par = new JSONObject();
                DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
                LocalDateTime value = dateTimePicker.dateTimeProperty().getValue();
                String format = df.format(value);
                par.put("ids",ids);
                par.put("name",format);
                Http.post("/tmsshipment/arrived", par, new HttpCall() {
                    @Override
                    public void exe(ReturnModel returnModel) {
                        if (returnModel.isSuceess()){
                            NoticeUtils.success(returnModel.getObj().toString());
                            queryList();
                            updateMainData();
                        }else {
                            NoticeUtils.error(returnModel.getObj().toString());
                        }

                    }
                });
            }
        });
        winTool.setButton(button);
        winTool.show();
    }
}
